package in.co.codedoc.json;

import java.util.ArrayList;

public class JSONArrayValue
	extends JSONValue
{
	public JSONArrayValue()
	{
		this(new ArrayList<JSONValue>());
	}
	
	public JSONArrayValue(ArrayList<JSONValue> entries)
	{
		this.entries = entries;
	}
	
	public JSONArrayValue(JSONValue jsonValue)
	{
		if(jsonValue instanceof JSONArrayValue)
		{
			this.entries = ((JSONArrayValue)jsonValue).entries;
		}
		else
		{
			this.entries = new ArrayList<JSONValue>();
			if(jsonValue != null)
			{
				this.entries.add(jsonValue);
			}
		}
	}
	
	public int GetNumEntries()
	{
		return entries.size();
	}
	
	public JSONValue GetEntry(int index)
	{
		return entries.get(index);
	}
	
	public static class ForEach<T>
	{
		public void Do(int index,JSONValue value)
		{
			
		}
		
		public T Do(int index,JSONValue value,T t)
		{
			return t;
		}
	}
	
	public <T> void ForEach(ForEach<T> fe)
	{
		int index = 0;
		
		for(JSONValue v:entries)
		{
			fe.Do(index++, v);
		}
	}
	
	public <T> T ForEach(ForEach<T> fe,T t)
	{
		int index = 0;
		
		for(JSONValue v:entries)
		{
			t = fe.Do(index++, v,t);
		}
		
		return t;
	}

	@Override
	public StringBuffer Encode(final StringBuffer buffer)
	{
		buffer.append('[');
		
		ForEach
		(
			new ForEach<Object>()
			{
				public void Do(int index,JSONValue v)
				{
					if(index > 0)
					{
						buffer.append(',');
					}
					v.Encode(buffer);
				}
			}
		);
		
		buffer.append(']');
		
		return buffer;
	}

	@Override
	public boolean equals(Object t)
	{
		if((t == null) || !(t instanceof JSONArrayValue))
		{
			return false;
		}

		JSONArrayValue that = (JSONArrayValue)t;
		
		return that.entries == entries;
	}

	@Override
	public int hashCode()
	{
		return entries.hashCode();
	}


	public void Add(JSONValue entry)
	{
		entries.add(entry);
	}
	
	private ArrayList<JSONValue> entries;
}
